<template>
	<view class="homeOrdering page">
		<up-toast ref="uToastRef"></up-toast>
		<view class="driverDetailTop">
			<view>
				<image src="../../static/start.png"></image>
				<text>{{details.startPlace}}</text>
			</view>
			<view>
				<image src="../../static/end.png"></image>
				<text>{{details.stopPlace}}</text>
			</view>
		</view>
		<view class="orderDetail">
			<view class="naviga" @click="handleNavigation">
				<up-icon name="map-fill" color="#3C9CFF" size="18px"></up-icon>{{navigatorText}}
			</view>
			<view class="phone" @click="handleCall">
				<up-icon name="phone-fill" color="#3C9CFF" size="18px"></up-icon>联系客户
			</view>
		</view>
		<view class="btn-box" v-show="details.isAcceptOrder == 1 || details.isAcceptOrder == 2">
			<up-button  @click="handleOrderGo(details)" :loading="orderLoading" type="primary" :text="details.isAcceptOrder == 1 ? '开始派单' : '结束订单'"></up-button>
			<!-- <up-button type="primary" @click="startRecord" text="录音测试"></up-button>
			<up-button type="primary" @click="stopRecord" text="停止录音"></up-button>
			<up-button type="primary" @click="playRecord" text="播放录音"></up-button>
			<up-button v-show="details.isAcceptOrder == 1" @click="handleOrderCancle(details.id)" type="primary" plain text="取消订单" :loading="cancelLoading"></up-button> -->
		</view>
		<up-modal :show="show"  @confirm="confirm" title="提示" :content='content' :asyncClose="true"></up-modal>
	</view>
</template>

<script setup>
	import http from "@/request/index.js"
	const ttsModule = ref(null);
	const show = ref(false);
	const status = ref('');
	const details = ref({});
	const navigatorText = ref('导航去找用户');
	const latitude = ref('');
	const longitude = ref('');
	const name = ref('');
	const address = ref('');
	const selfLocation = ref({
		latitude: '',
		longitude: ''
	});
	const orderLoading = ref(false);
	const cancelLoading = ref(false);
	const timer = ref(null);
	
	onMounted(() => {
		ttsModule.value = uni.requireNativePlugin("hm-tts-TtsModule")
		ttsModule.value.init((ret) => {});
		getInfo();
		isCancelOrder();
		timer.value && clearInterval(timer.value)
		timer.value = setInterval(() => { // 113.61302, 34.74811
		  isCancelOrder()
		}, 5000)
	})
	onUnload(() => {
		timer.value && clearInterval(timer.value)
		timer.value = null
	})
	const onPullDownRefresh = () => {
		getInfo()
	}
	
	const isCancelOrder = async() => {
		let { code, msg, data } = await http('/app/order/getOrderFromInProgress', 'GET')
		console.log('订单已取消~', data)
		if (code != 200) return uni.showToast({ title: msg, icon: "none" })
		if (data.quxiao) {
			ttsModule.value.speak({text: '订单已被取消~ 订单已被取消~ 订单已被取消~'})
			uni.showToast({ title: '订单已被取消~', icon: 'none' })
			uni.switchTab({ url: '/pages/home/index' })
		}
	}
	
	const startRecord = () => {
		getApp().startRecord()
	}
	const stopRecord = (id) => {
		getApp().stopRecord(id)
	}
	const playRecord = () => {
		getApp().playRecord()
	}
	const getInfo = async() => {
		let { code, msg, data } = await http('/app/order/getOrderFromInProgress', 'GET')
		if (code != 200) return uni.showToast({ title: msg, icon: "none" })
		console.log(data)
		navigatorText.value = data.isAcceptOrder == 1 ? '导航去找客户' : data.isAcceptOrder == 2 ? '导航去目的地' : ''
		details.value = data
	}
	const handleCall = () => {
		console.log(11223, details.value.byTel)
		uni.makePhoneCall({
			phoneNumber: details.value.byTel
		});
	}
	const handleFinish = () => {
		uni.navigateBack()
	}
	const handleOrderGo = (isAcceptOrder) => {
		show.value = true
		if (isAcceptOrder == 1) { // 已接单未派送
			content.value = "确定开启订单？"
		} else {
			content.value = "已将客户车辆送到指定地点，确定订单结束？"
		}
	}
	const confirm = async() => {
		let { isAcceptOrder, id, isAppletOrder } = details.value
		if (isAcceptOrder == 1) { // 已接单未派送
			orderLoading.value = true
			let { code, msg, data } = await http(`/app/order/updateOrderIsAccept/${id}`, 'GET')
			orderLoading.value = false
			if (code != 200) return uni.showToast({ title: msg, icon: 'none' })
			getInfo()
			uni.showToast({ title: '开始派送中', icon: 'none' })
			show.value = false
			startRecord()
		} else {
			orderLoading.value = true
			let { code, msg, data } = await http(`/app/order/updateOrderComplete`, { orderId: id },'POST')
			console.log(11111111111111112, code, msg, data)
			orderLoading.value = false
			if (code != 200) return uni.showToast({ title: msg, icon: 'none' })
			stopRecord(data.id)
			uni.showToast({ title: '订单已结束，辛苦啦~', icon: 'none' })
			getInfo()
			show.value = false
			let userShouldMoney = data.userShouldMoney || 0
			uni.redirectTo({
				url: `/pages/homeOrder/payQrCode?id=${id}&money=${userShouldMoney}`
			})
		}
	}
	const handleOrderCancle = async(id) => {
		cancelLoading.value = true
		let { code, msg, data } = await http(`/app/order/upOrderCancellation/${id} `, 'GET')
		cancelLoading.value = false
		if (code != 200) return uni.showToast({ title: msg, icon: 'none' })
		uni.showToast({ title: '订单已取消', icon: 'none' })
		uni.switchTab({ url: '/pages/index/index' })
	}
	const handleNavigation = () => {
		let { startGps, stopGps, isAcceptOrder, startPlace, stopPlace } = details.value
		selfLocation.value = {
			longitude: getApp().globalData.longitude,
			latitude: getApp().globalData.latitude
		}
		if (isAcceptOrder == 1) {
			let [longitude, latitude] = startGps.split(',')
			name.value = startPlace
			longitude.value = longitude || 0
			latitude.value = latitude || 0
		} else if (isAcceptOrder == 2) {
			let [longitude, latitude] = stopGps.split(',')
			name.value = stopPlace
			longitude.value = longitude || 0
			latitude.value = latitude || 0
		}
		if (!latitude.value || !longitude.value || !name.value) return
		// #ifdef APP-PLUS
		// 判断系统安装的地图应用有哪些, 并生成菜单按钮
		let _mapName = [
		    {title: '高德地图', name: 'amap', androidName: 'com.autonavi.minimap', iosName: 'iosamap://'},
		    {title: '百度地图', name: 'baidumap', androidName: 'com.baidu.BaiduMap', iosName: 'baidumap://'},
		    {title: '腾讯地图', name: 'qqmap', androidName: 'com.tencent.map', iosName: 'qqmap://'},
		]
		// 根据真机有的地图软件 生成的 操作菜单
		let buttons = []
		let platform = uni.getSystemInfoSync().platform
		platform === 'android' && _mapName.forEach(item => {
		    if (plus.runtime.isApplicationExist({pname: item.androidName})) {
		        buttons.push(item)
		    }
		})
		platform === 'ios' && _mapName.forEach(item => {
			console.log(item.iosName)
			if (plus.runtime.isApplicationExist({action: item.iosName})) {
				buttons.push(item)
			}
		})
		if (buttons.length) {
			plus.nativeUI.actionSheet({ //选择菜单
				title: "选择地图应用",
				cancel: "取消",
				buttons: buttons
			}, function (e) {
				let _map = buttons[e.index - 1]
				openURL(_map, platform)
			})
		} else {
			uni.showToast({ title: '请安装地图软件(推荐：高德/百度/腾讯)', icon: 'none' })
			return
		}
		// #endif
	}
	// 打开第三方程序实际应用
	const openURL = (map, platform) => {
		let _defaultUrl = {
			android: {
				"amap": `amapuri://route/plan/?sid=&did=&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
				'qqmap': `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
				'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo"`
			},
			ios: {
				"amap": `iosamap://path?sourceApplication=fuxishan_uni_client&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
				'qqmap': `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
				'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&mode=driving&src=ios.baidu.openAPIdemo`
			}
		}
		let newurl = encodeURI(_defaultUrl[platform][map.name]);
		console.log(newurl)
		plus.runtime.openURL(newurl, function(res){
			console.log(res)
			uni.showModal({
				content: res.message
			})
		}, map.androidName ? map.androidName : '');
	}
</script>

<style lang="scss" scoped>
	.homeOrdering {
		width: 100%;
		height: 100vh;
		background-color: #fff;
		.driverDetailTop {
			min-height: 110px;
			padding: 20px 15px;
			background-color: #F7F9FD;
			>view {
				margin-top: 10px;
			}
			image {
				width: 24px;
				height: 24px;
				vertical-align: top;
			}
			text {
				display: inline-block;
				width: calc(100% - 40px);
				vertical-align: top;
				font-size: 16px;
				font-weight: bold;
			}
		}
		.orderDetail {
			text-align: center;
			.naviga {
				display: inline-block;
				border: 1px solid #3C9CFF;
				color: #3C9CFF;
				font-size: 16px;
				width: 120px;
				padding: 4px 10px;
				margin-right: 10px;
			}
			.phone {
				display: inline-block;
				width: 100px;
				padding: 4px 10px;
				margin-top: 50px;
				font-size: 16px;
				text-align: center;
				color: #3C9CFF;
				border: 1px solid #3C9CFF;
				margin: 50px auto;
			}
		}
		.btn-box {
			text-align: center;
			.u-button {
				width: 120px;
				line-height: 40px;
				display: inline-block;
				margin: 0 15px;
			}
			.u-count-down {
				display: inline-block;
			}
		}
	}
</style>

<style lang="scss">
.homeOrdering {
	::v-deep .u-count-down__text {
		color: #fff!important;
	}
	.u-icon {
		display: inline-block!important;
	}
}
</style>
